<%--
  Created by IntelliJ IDEA.
  User: aHao
  Date: 2020/10/28
  Time: 15:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head lang="zh-CN">
    <meta charset="UTF-8">
    <title>ssm_crud</title>
    <%--    获取bootstrap框架--%>
    <jsp:include page="/WEB-INF/publicJsp/bootstrap.jsp"/>
    <script charset="UTF-8" type="text/javascript">
        // 页面数数据
        let pageInfo;
        //页面初始化
        $(function (){
            $.ajax({
                type:"POST",
                url:"/ssm_crud/emps",
                date:"pn=1",
                dataType:"JSON",
                success:function (result){
                    pageInfo=result.extend.pageInfo
                    //第一步往员工表格中添加数据
                    add_emp_table(result)
                    //第二步添加分页信息
                    add_pageInfo(result)
                    //第三部添加分页行
                    add_pageNum_row(result)
                    //第四设置员工添加表单信息
                    conf_emp_add_form()
                    // 第五设置员工修改表单信息
                    conf_emp_update_form()
                    //配置选择删除
                    conf_check_delete()
                }
            })

            // 展示验证信息
            function show_validate_msg($ele,status,msg){
                if (status){
                    $ele.parent().parent().attr("class","form-group has-success")
                    $ele.next().text("")
                    return true
                }else{
                    $ele.parent().parent().attr("class","form-group has-error")
                    $ele.next().text(msg)
                    return false
                }
            }

            //设置员工添加表单
            function conf_emp_add_form(){
                // 1，将部门信息放入下拉选择栏中
                // 发送ajax请求获取部门信息,并设置
                conf_form_dept(".emp_add_form")

                $("#empName_add_input").change(function () {
                    //在服务器中验证用户名是否存在
                    $.ajax({
                        type:"POST",
                        url:"/ssm_crud/checkUser",
                        data: "empName="+$("#empName_add_input").val(),
                        dataType:"JSON",
                        success:function (result) {
                            if (result.code==200){
                                show_validate_msg($("#empName_add_input"),false,result.msg)
                                $(".emp_add_form_submit").attr("ajax-va","error")
                            }else {
                                show_validate_msg($("#empName_add_input"),true,result.msg)
                                $(".emp_add_form_submit").attr("ajax-va","success")
                            }
                        }
                    })
                })

                // 2，模态框的save按钮的点击事件调剂数据保存
                // 获取表单$对象
                let $empAddForm = $(".emp_add_form");
                //获取按钮$对象 点击提交。
                $(".emp_add_form_submit").click(function (){
                    // //对表单数据进行验证
                    if (!validate_add()){
                        return
                    }

                    //服务器的验证
                    if($(this).attr("ajax-va")=="error"){
                        return
                    }

                    function validate_add(){
                        let isSuccess=true
                        // 验证员工姓名
                        let $empNameInput = $("#empName_add_input")
                        let empNameVal = $empNameInput.val();
                        let regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/
                        if (!show_validate_msg($empNameInput,regName.test(empNameVal),"姓名应该是2-5个中文或者6-16个英文")){
                            isSuccess=false
                            return isSuccess
                        }
                        //验证邮箱
                        let $emailAddInput = $("#email_add_input");
                        let emailVal = $emailAddInput.val()
                        let regEmail=/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
                        if (!show_validate_msg($emailAddInput,regEmail.test(emailVal),"请输入正确的邮箱")){
                            isSuccess=false
                            return isSuccess
                        }

                        return isSuccess
                    }

                    // 保存用户信息
                    $.ajax({
                        type:"POST",
                        url:"/ssm_crud/emp",
                        data: $empAddForm.serialize(),
                        dataType:"JSON",
                        success:function (result){
                            // 后台验证成功
                            if (result.code=="100"){
                                // 数据保存后的操作
                                // 1，跳出数据操作的信息，然后关闭模态框
                                alert(result.msg)
                                $("#emp_add_modal").modal("hide")
                                // 2，跳到最后一页显示刚添加的数据
                                // 获取最后一页的页数，总数据量，每页的数据量
                                let lastPage = pageInfo.lastPage;
                                let total = pageInfo.total;
                                let pageSize = pageInfo.pageSize;
                                // 判断最后页数据是否已经满了
                                if (total%pageSize==0&&total!=0){
                                    lastPage++
                                }
                                // 跳转到最后一页
                                pageNum_button(lastPage)
                            }else {
                                // 获取错误信息的map
                                let errorMap = result.extend.errorMap;
                                //对错误信息作出相应的动作
                                if (errorMap.empName!=undefined){
                                    show_validate_msg($("#empName_add_input"),false,errorMap.empName)
                                }else{
                                    show_validate_msg($("#email_add_input"),false,errorMap.email)
                                }
                            }
                        }
                    })

                })
            }
            //设置员工修改模态框
            function conf_emp_update_form(){

                // 1,将部门信息放入表单中
                conf_form_dept(".emp_update_form")
                //2,设置修改提交点击事件
                $(".emp_update_form_submit").click(function (){
                    //1，先验证邮箱
                    // //对表单数据进行验证
                    if (!validate_update()){
                        return
                    }

                    function validate_update(){
                        //验证邮箱
                        let $emailUpdateInput = $("#email_update_input");
                        let emailVal = $emailUpdateInput.val()
                        let regEmail=/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
                        if (!show_validate_msg($emailUpdateInput,regEmail.test(emailVal),"请输入正确的邮箱")){
                            return false
                        }

                        return true
                    }
                    //2,提交给服务器
                    $.ajax({
                        type:"POST",
                        url:"/ssm_crud/emp",
                        data: "_method=PUT&"+$(".emp_update_form").serialize(),
                        dataType:"JSON",
                        success:function (result){
                            // 后台验证成功
                            if (result.code=="100"){
                                // 数据保存后的操作
                                // 1，跳出数据操作的信息，然后关闭模态框
                                alert(result.msg)
                                $("#emp_update_modal").modal("hide")

                                //2 刷新页面
                                pageNum_button(pageInfo.pageNum)
                            }else {
                                // 获取错误信息的map
                                let errorMap = result.extend.errorMap;
                                //对错误信息作出相应的动作
                                if (errorMap.empName!=undefined){
                                    show_validate_msg($("#empName_add_input"),false,errorMap.empName)
                                }else{
                                    show_validate_msg($("#email_add_input"),false,errorMap.email)
                                }
                            }
                        }
                    })
                })

            }
            function conf_form_dept(selected){
                $.ajax({
                    type:"GET",
                    url:"/ssm_crud/depts",
                    dataType:"JSON",
                    success:function (result){
                        // 获取下拉框的对象
                        let $deptSelect = $(selected+" .dept_select");
                        //获取部门信息的集合
                        let depts = result.extend.depts;
                        //遍历集合并放入下拉框中
                        for (let i = 0; i < depts.length; i++) {
                            let dept = depts[i];
                            $deptSelect.append($("<option></option>").append(dept.deptName).attr("value",dept.deptId))
                        }
                    }
                })
            }
            // 添加分页行的函数
            function add_pageNum_row(result){
                //首先要获取分页信息对象
                let pageInfo = result.extend.pageInfo;
                // 获取装载分页行的容器
                let $pagination = $(".pagination")

                //添加首页按钮
                $pagination.append($("<li></li>").append($("<a href='#'>首页</a>").click(function (){pageNum_button(pageInfo.firstPage)})))
                //添加上一页按钮
                if(pageInfo.hasPreviousPage){
                    $pagination.append($("<li><a href='#' aria-label='Previous'>" +
                        "<span aria-hidden='true'>&laquo;</span></a></li>").click(function (){pageNum_button(--pageInfo.pageNum)}))
                }

                // 添加中间的页码按钮
                // 1，获取页码集合
                let navigatepageNums = pageInfo.navigatepageNums;
                // 2,遍历集合，添加页码按钮
                for (let i = 0; i < navigatepageNums.length;i++) {
                    // 当前页码明亮的类名值
                    let classValue="";
                    if(pageInfo.pageNum==navigatepageNums[i]){
                        classValue="active";
                    }
                    $pagination.append($("<li class=\""+classValue+"\"><a href='#'>"+navigatepageNums[i]+"</a></li>").click(function (){pageNum_button(navigatepageNums[i])}))
                }

                //添加下一页按钮
                if(pageInfo.hasNextPage){
                    $pagination.append($("<li><a href='#' aria-label=\"Next\">" +
                        "<span aria-hidden=\"true\">&raquo;</span></a></li>").click(function (){pageNum_button(++pageInfo.pageNum)}))
                }
                //添加尾页页按钮
                $pagination.append($("<li></li>").append($("<a href='#'>尾页</a>").click(function (){pageNum_button(pageInfo.lastPage)})))

            }
            // 分页行按钮的点击函数 pageNum是要页码
            function pageNum_button(pageNum){
                console.log("................")
                $.ajax({
                    type:"POST",
                    url:"/ssm_crud/emps",
                    data:"pn="+pageNum,
                    dataType: "JSON",
                    success:function (result){
                        pageInfo=result.extend.pageInfo
                        //1,清空员工表里面所有的数据
                        $(".emp_table>tbody").empty()
                        //2,清空分页行里面所有的按钮
                        $(".pagination").empty()
                        //3，添加表内信息
                        add_emp_table(result)
                        //4,添加分行信息
                        add_pageNum_row(result);
                    }
                })
            }

            // 添加分页信息的函数
            function add_pageInfo(result){
                // 首先要获取分页信息对象
                let pageInfo = result.extend.pageInfo;
                //获取装数据的容器
                let $pageInfo = $(".pageInfo");
                // 将数据放入容器中
                $pageInfo.append("当前页："+pageInfo.pageNum+"   总页数："+pageInfo.pages+"  总数据量："+pageInfo.total)

            }
            //往员工表中添加数据的函数
            function add_emp_table(result){
                // console.log(result)
                // 获取员工数据的集合
                let emps = result.extend.pageInfo.list;
                //往员工里添加数据
                //1，获取装数据的容器
                let $tbody = $(".emp_table>tbody");
                // 2，遍历员工集合，添加行
                for (let i = 0; i < emps.length; i++) {
                    let emp = emps[i];
                    let $tr=$("<tr></tr>")
                        .append($("<td><input type='checkbox' class='check-delete'></td>"))
                        .append($("<td>"+emp.empId+"</td>"))
                        .append($("<td>"+emp.empName+"</td>"))
                        .append($("<td>"+emp.gender+"</td>"))
                        .append($("<td>"+emp.email+"</td>"))
                        .append($("<td>"+emp.department.deptName+"</td>"))
                        .append($("<td></td>")
                            .append($("<button class=\"btn btn-primary btn-small update-btn\"><span class=\"glyphicon glyphicon-pencil\" aria-hidden=\"true\"/>修改</button>").click(
                                function (){update_btn(emp.empId)}
                            ))
                            .append($("<button class=\"btn btn-danger btn-small delete-btn\"><span class=\"glyphicon glyphicon-remove\" aria-hidden=\"true\"/>删除</button>").click(
                                function () {
                                    delete_btn(emp.empId)
                                }
                            ))
                        )

                    $tbody.append($tr)
                }

                /**
                 * 修改按钮的点击事件函数
                 * @param empId 需要修改的员工的id
                 */
                function update_btn(empId){
                    // 1，向修改表单注入员工数据
                    $.ajax({
                        type:"GET",
                        url:"/ssm_crud/emp",
                        data:"empId="+empId,
                        dataType:"JSON",
                        success:function (result) {
                            // 获取员工对象
                            let emp = result.extend.emp;
                            // 注入数据
                            $("#empId_update_input").val(emp.empId)
                            $("#empName_update_input").val(emp.empName)
                            $("#email_update_input").val(emp.email)
                            $(".radio-inline>input").each(function (index,domEle){
                                  if ($(domEle).val()==emp.gender){
                                        $(domEle).attr("checked","checked")
                                  }
                            })
                            $(".dept_select>option").each(function (index,domEle){
                                if ($(domEle).val()==emp.dId){
                                    $(domEle).attr("selected","selected")
                                }
                            })
                        }
                    })
                    // 2，弹出员工数据修改模态框
                    $("#emp_update_modal").modal("show")
                }

                /**
                 * 删除按钮的点击事件函数
                 * @param empId
                 */
                function delete_btn(empId){
                    //确认是否要删除
                    if (confirm("是否要删除id为"+empId+"的员工？")){
                       //删除
                       $.ajax({
                           type:"POST",
                           url:"/ssm_crud/emp",
                           data:"_method=delete&empId="+empId,
                           dataType:"JSON",
                           success:function (result){
                                //刷新页面
                               pageNum_button(pageInfo.pageNum)
                           }
                       })
                    }
                }
            }
            //设置多选删除
            function conf_check_delete(){
                //设置全选或者全部选的动态选择
                // 获取全选复选框
                // 获取当前页所有的删除复选框
                let $checkDelete = $(".check-delete");
                $("#check-delete-input").change(function () {
                    if ($("#check-delete-input").prop("checked")){
                        $checkDelete.each(function(index,eleDom) {
                                $(eleDom).prop("checked",true)
                            }
                        )
                    }else{
                        $checkDelete.each(function(index,eleDom) {
                                $(eleDom).prop("checked",false)
                            }
                        )
                    }
                })

                //设置多选按钮删除按钮
                $(".check-delete-btn").click(function () {
                    // 确认是否删除
                    if (confirm("是否删除?")){
                        // 获取所有要删的id，用字符“-”拼接起来
                        let ids="";
                        $checkDelete.each(function (index,eleDom) {
                            let $eleDom = $(eleDom);
                            if ($eleDom.prop("checked")){
                                // 获取相应的id
                                let id = $eleDom.parents("tr").find("td:eq(1)").text();
                                ids += id+"-"
                            }
                        })

                        // 判断是否所有的都没有选中
                        if(ids==""){
                            alert("请选择后再点击删除")
                            return
                        }else {
                            ids = ids.substr(0,ids.length-1)
                        }

                        //执行删除的ajax请求
                        $.ajax({
                            type:"POST",
                            url:"/ssm_crud/emps",
                            data:"_method=DELETE&ids="+ids,
                            dataType:"JSON",
                            success:function (result) {
                                // 成功就刷新页面
                                if (result.code==100){
                                    pageNum_button(pageInfo.pageNum)
                                }
                            }
                        })
                    }
                })
            }
        })
    </script>
</head>
<body>
<!-- 新增表单的模态框 -->
<div class="modal fade" id="emp_add_modal" tabindex="-1" role="dialog" aria-labelledby="add_ModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="add_ModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
<%--                新增员工表单--%>
                <form class="form-horizontal emp_add_form" action="/ssm_crud/emp" method="POST">
                    <div class="form-group">
                        <label for="empName_add_input" class="col-sm-2 col-sm-offset-2 control-label">empName</label>
                        <div class="col-sm-5">
                            <input type="text" class="form-control" id="empName_add_input" name="empName" placeholder="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 col-sm-offset-2 control-label">email</label>
                        <div class="col-sm-5">
                            <input type="text" class="form-control" id="email_add_input" name="email" placeholder="email@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 col-sm-offset-2 control-label">gender</label>
                        <div class="col-sm-5">
                            <label class="radio-inline">
                                <input type="radio" name="gender"  value="男" checked>男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender"  value="女">女
                            </label>
                        </div>
                    </div><div class="form-group">
                        <label class="col-sm-2 col-sm-offset-2 control-label">部门</label>
                        <div class="col-sm-5">
                            <select class="form-control dept_select" name="dId">
                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary emp_add_form_submit">Save</button>
            </div>
        </div>
    </div>
</div>
<%--修改表单的模态框--%>
<div class="modal fade" id="emp_update_modal" tabindex="-1" role="dialog" aria-labelledby="update_ModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="update_ModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <%--                新增员工表单--%>
                <form class="form-horizontal emp_update_form" method="POST">
                    <input type="hidden" name="empId" id="empId_update_input">
                    <div class="form-group">
                        <label for="empName_update_input" class="col-sm-2 col-sm-offset-2 control-label">empName</label>
                        <div class="col-sm-5">
                            <input type="text" class="form-control-static" id="empName_update_input" name="empName" placeholder="empName" disabled>
                            <span class="help-block"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 col-sm-offset-2 control-label">email</label>
                        <div class="col-sm-5">
                            <input type="text" class="form-control" id="email_update_input" name="email" placeholder="email@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 col-sm-offset-2 control-label">gender</label>
                        <div class="col-sm-5">
                            <label class="radio-inline">
                                <input type="radio" name="gender" value="男">男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" value="女">女
                            </label>
                        </div>
                    </div><div class="form-group">
                    <label class="col-sm-2 col-sm-offset-2 control-label">部门</label>
                    <div class="col-sm-5">
                        <select class="form-control dept_select" name="dId">
                        </select>
                    </div>
                </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary emp_update_form_submit">update</button>
            </div>
        </div>
    </div>
</div>
<%--    内容容器--%>
<div class="container">
    <%--        标题行--%>
    <div class="row">
        <div class="col-lg-12">
            <h1>ssm_crud</h1>
        </div>
    </div>
    <%--        按钮行--%>
    <div class="row">
        <div class="col-lg-4 col-lg-offset-8">
            <button class="btn btn-success" data-toggle="modal" data-target="#emp_add_modal"><span class="glyphicon glyphicon-plus" aria-hidden="true"/>新增</button>
            <button class="btn btn-danger check-delete-btn"><span class="glyphicon glyphicon-remove" aria-hidden="true"/>删除</button>
        </div>
    </div>
    <%--        数据表行--%>
    <div class="row">
        <table class="table table-hover emp_table">
            <thead>
            <tr>
                <td><input type="checkbox" id="check-delete-input"></td>
                <td>#</td>
                <td>name</td>
                <td>gender</td>
                <td>email</td>
                <td>department</td>
                <td>action</td>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <%--        数据信息行--%>
    <div class="row">
        <div class="col-lg-3 col-lg-offset-4 pageInfo">

        </div>
    </div>
    <%--        分页按钮行    --%>
    <div class="row">
        <div class="col-lg-4 col-lg-offset-4">
            <nav aria-label="Page navigation">
                <ul class="pagination"></ul>
            </nav>
        </div>
    </div>
</div>
</body>
</html>